<template>
    <div class="common-layout">
      <el-container>
        <el-card class="box-card">
            <el-header class="model-selection" style="padding: 0">
              <div style="margin-left: 50vw">
                <span>文言一心 对话</span>
              </div>
              <div style="float: right">
              <span class="mx-1" type="success"  style="text-align: right;">用户对话记录最多保存1200字的长度，超过长度将会重置</span>
              </div>
            </el-header>
            <el-aside style="width: 15vw;float: left;border-right: 1px solid black;">
              <el-button style="margin-top: 4vh" @click="clear"   >清空对话记录</el-button>
            </el-aside>
            <!-- 消息容器 -->
            <div class="message-container" ref="messageContainer">
              <div v-for="(message, index) in messages" :key="index" class="message-item" :class="{ 'user-message': message.isUser, 'bot-message': !message.isUser }">
                <el-card>
                  <template #header>
                    <div v-if="message.role == 'user'" class="card-header">
                      <el-avatar> user </el-avatar>
                      <div>
                      <el-avatar src="https://www.rhzhz.cn/wp-content/uploads/2023/11/20220714222919_c0aa1.thumb_.1000_0.jpg"
                      />
                      </div>
                      </div>
                    <div v-else class="card-header">
                      <div>
                        <el-avatar src="https://www.rhzhz.cn/wp-content/uploads/2022/08/Gravity_Falls_BillCipherCursor.png"
                        />
                      </div>
                      <el-avatar> robot </el-avatar>
                    </div>
                  </template>
                <p>{{ message.content }}</p>
                  <!-- <div v-else-if="message.content" class="text-message" v-html="parseMarkdown(message.content)"></div>
                <p v-else-if="message.error" class="error-message">{{ message.content }}</p> -->
                </el-card>
                <el-button @click="copyText(message.content)">复制文本</el-button>
              </div>

            </div>
            <div class="chat-input">
              <el-input :disabled="robotIsReplying" v-model="userInput" type="textarea" autosize placeholder="请输入消息"></el-input>
              <el-button :disabled="robotIsReplying" @click="sendMessage" type="primary">发送</el-button>
            </div>
          </el-card>
      </el-container>
    </div>
  </template>

<script>
import { getAccessToken} from '@/api/ERNIEBot';
import axios from 'axios';
// import MarkdownIt from 'markdown-it';
export default
{
  data() {
    return {
      userInput: '',
      messages: [],
      robotIsReplying: false, // 用于标识机器人是否正在回复
      selectedModel: 'gpt-3.5-turbo', // 默认选择 GPT-4
      textToCopy: '要复制的文本内容',
      // 在 data 中添加用于存储用户输入历史的变量
      chatHistory: [],  // 用于存储对话历史
      accessToken:''
    };
  },
  methods: {
    parseMarkdown(text) {
      console.log(text);
    },
    copyText(text) {
      navigator.clipboard.writeText(text).then(() => {
        alert('文本已成功复制到剪贴板');
      }).catch((error) => {
        alert('文本复制失败：' + error);
      });
    },
    clear(){
      this.userInput= '',
      this.chatHistory=[] , // 用于存储对话历史
      this.messages=[]
      this.saveChatHistory()
    },
    
    sendMessage() {
      this.messages.push({
        'role':'user',
        'content':this.userInput
      })
      axios({
        method:'post',
        url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token='+this.accessToken,
        data: {
          'messages':this.messages
        },
        headers: {
            'Content-Type': "application/json"
        }
      })
      .then(res=>{
        this.messages.push({
          'role':'assistant',
          'content':res.data.result
        })
        this.userInput = ''

        this.chatHistory = this.messages
        this.saveChatHistory()
      })

    },
    
    // 将对话历史保存到本地存储
    saveChatHistory() {
      this.$store.commit('setChatHistory',this.chatHistory)
    },
    getChatHistory() {
      this.chatHistory = this.$store.state.chatHistory
    }

  },
  mounted() {
    //取出对话历史
    this.getChatHistory()
    if (this.chatHistory != null && this.chatHistory.length != 0)
    {
      this.messages = this.chatHistory
      console.log(this.chatHistory)
    }
    else if (this.messages.length == 0||this.accessToken != ''){
      axios({
        method:'post',
        url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token='+this.accessToken,
        data: {
          'messages':[{
            'role':'user',
            'content':'你好'
          }]
        },
        headers: {
            'Content-Type': "application/json"
        }
      })
      .then(res=>{
        this.messages.push({
            'role':'user',
            'content':'你好'
          })
        this.messages.push({
          'role':'assistant',
          'content':res.data.result
        })
      })
    }
  },
  created(){
    //获取文言一心token
    this.accessToken = this.$store.state.accessToken
    if (this.accessToken == ''||this.accessToken == null){
      getAccessToken().then(res =>{
        if (res.code == 1){
          this.accessToken = res.data.accessToken
          this.$store.commit('setAccessToken',this.accessToken)
        }
      })
    }
  }
};
</script>

<style scoped>
.common-layout {
  height: 100vh; /* 设置布局高度为整个视口高度 */
  display: flex;
  justify-content: center;
  align-items: center;
}


.user-message, .bot-message {

  margin-bottom: 30px;
}

.user-message {
  /*margin-left: 50vw;*/
  /*background-color: #d4edda; !* 设置用户消息的背景色 *!*/
  text-align: right;
}

.bot-message {
  /*margin-right: 50vw;*/
  text-align: left;
}

.chat-input {
/*position: absolute;*/
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 0px;
  margin-left: 20vw;
  margin-top: 55vh;
  background-color: #ffffff;
}

.chat-input el-input {
  flex: 1;
  margin-right: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box-card {
  margin:0 auto;
  width: 97vw;
  height: 90vh; /* 注意这里添加了分号 */
  position: relative; /* 让卡片成为定位上下文 */
  /*height: 500px; !* 假设卡片容器有固定高度 *!*/
  overflow: auto; /* 如果需要滚动条的话 */
}
/* 添加打字效果的样式 */
.typing-indicator {
  display: inline-block;
  overflow: hidden;
  position: relative;
  width: 0;
}

.typing-indicator:before {
  display: block;
  content: "|"; /* 使用竖线作为光标 */
  width: 0;
  height: 0;
  position: absolute;
  top: 0;
  right: 0;
  animation: typing 0.5s steps(30, end) infinite; /* 使用 steps 函数来模拟逐字显示 */
}
@keyframes typing {
  from { width: 0; }
  to { width: auto; }
}

.error-message {
  color: red;
  font-style: italic;
}
.text-message {
  margin: 10px 0;

}
@keyframes typing {
  0% {
    height: 0;
  }
  50% {
    height: 1em;
  }
  100% {
    height: 0;
  }
}
/* 可以根据需求自定义样式 */
.chat-container {
  width: 100vw;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: 100vh; /* 设置容器高度为视口高度，保证内容超出时可以滚动 */
}

.message-container {
 
  overflow-y: auto; /* 设置内容超出时显示滚动条 */
  margin-left:  auto;
  float: right;
  width: 73vw;
  max-height: 50vh;
  padding: 10px;
}
.user-message {
  text-align: right;
  /*background-color: #d4edda; !* 设置用户消息的背景色 *!*/
}

.bot-message {
  text-align: left;
  /*background-color: #f0f0f0; !* 设置ChatGPT消息的背景色 *!*/
}
.input-container {
  position: absolute; /* 将输入框容器设置为绝对定位 */
  bottom: 0; /* 将输入框容器放置在底部 */
  width: 100%; /* 设置输入框容器的宽度为100% */
  padding: 10px; /* 添加内边距 */
  display: flex; /* 使用 Flex 布局 */
  justify-content: space-between; /* 调整输入框和发送按钮之间的间距 */
}

</style>